package models

import (
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
	"time"
)

// 捐赠记录表
type MJuanZeng struct {
	ID         int             `gorm:"type:int(11); primaryKey" json:"id"`
	Aid        int             `gorm:"type:int(11);" json:"aid"`
	Mid        int             `gorm:"type:int(11);" json:"mid"`           //捐赠人id
	Name       string          `gorm:"type:varchar(255);" json:"name"`     //捐赠人名称
	Orderid    int             `gorm:"type:int(11);" json:"orderid"`       //订单ID
	Ordernum   string          `gorm:"type:varchar(255);" json:"ordernum"` //订单号
	Totalprice decimal.Decimal `json:"totalprice"`                         //支付总金额
	JuanPrice  decimal.Decimal `json:"juan_price"`                         //捐赠金额
	Juan       decimal.Decimal `json:"juan"`                               //捐赠比例
	JuanName   string          `json:"juan_name"`                          //捐赠对象
	IsJuan     int             `json:"is_juan"`                            //是否颁发证书
	CreatedAt  int             `gorm:"type:int(11);" json:"created_at"`
	UpdatedAt  int             `gorm:"type:int(11);" json:"updated_at"`
}

func (table *MJuanZeng) TableName() string {
	return "m_juan_zeng"
}

func JuanAdd(tx *gorm.DB, price decimal.Decimal, totalprice decimal.Decimal, mid int, Ordernum string, Orderid int, aid int) error {
	//查询信息设置信息
	var adminData MAdminSet
	err := tx.Model(new(MAdminSet)).Where("aid=?", aid).First(&adminData).Error
	if err != nil {
		return err
	}
	//查询用户信息
	var userData MMember
	err = tx.Model(new(MMember)).Where("id=?", mid).First(&userData).Error
	if err != nil {
		return err
	}
	//写入捐献记录
	var JuanData MJuanZeng
	JuanData.Aid = aid
	JuanData.Mid = mid
	JuanData.Name = userData.Nickname
	JuanData.Orderid = Orderid
	JuanData.Ordernum = Ordernum
	JuanData.Totalprice = totalprice
	JuanData.JuanPrice = price
	JuanData.JuanName = adminData.JuanName
	JuanData.Juan = adminData.Juan
	if userData.IsJuan == 1 {
		JuanData.IsJuan = 1
	} else {
		JuanData.IsJuan = 0
	}
	JuanData.CreatedAt = int(time.Now().Unix())
	err = tx.Model(new(MJuanZeng)).Create(&JuanData).Error
	if err != nil {
		return err
	}
	//用户升级和增加捐款总金额
	if userData.Levelid == 1 {
		var editData = map[string]interface{}{
			"levelid":    2,
			"is_juan":    1,
			"juan_price": gorm.Expr("juan_price+?", price),
		}
		err = tx.Model(new(MMember)).Where("id=?", mid).Updates(&editData).Error
		if err != nil {
			return err
		}
	} else {
		var editData = map[string]interface{}{
			"is_juan":    1,
			"juan_price": gorm.Expr("juan_price+?", price),
		}
		err = tx.Model(new(MMember)).Where("id=?", mid).Updates(&editData).Error
		if err != nil {
			return err
		}
	}

	return nil
}
